 // 写文件操作
 function writeFiles(path,content) {
    return new Promise(function(resolve,reject) {
        var fs = require('fs')
        let contentStr = content + '\n'
        fs.writeFile(path,contentStr,{flag: 'w'},function(err){
            if(err) {
                console.log('写入失败')
                reject(err)
            } else {
                console.log('写入成功')
                resolve(err) // 这里其实不需要传参数的
            }
        })
    })
}

// 读取文件操作
 function readFiles (path){
    return new Promise(function(resolve,reject) {
        var fs = require('fs')
        fs.readFile(path,{flag:'r',encoding:'utf-8'},function(err,data) {
            if (err) {
                reject(err)
            } else {
                resolve(data)
            }
        })
    })
}

// 创建目录操作
function mkDir (path) {
    return new Promise(function (resolve,reject) {
        var fs = require('fs')
        fs.mkdir(path, {recursive: true},function(err) {
            if (err) {
                console.log('创建目录失败')
                reject(err)
            } else {
                resolve('创建目录成功')
            }
        })
    })
}

// 请求流数据
function searchDate(url,attr) {
    let fs = require('fs')
    let axios = require('axios')
    const cheerio = require('cheerio') 
    return new Promise(function(resolve,reject) {
        axios.get(url,{responseType:'stream'}).then(res => {
            console.log('请求数据：',res)
            const $ = cheerio.load(res.data,{decodeEntities: false})
            let aurl = $(attr)
            let pageNum = $('.article-pagination .pagination>li').length -2
            let arr = []
            console.log('aurl==',aurl)
            aurl.each((i,item) => {
                let src = $(item).attr('src')
                let title = $(item).attr('title')
                console.log('标题：',title)
                arr.push({
                    src,title
                })
            })
            resolve(arr)
        }).catch(err => {
            reject('请求数据失败：',err)
        })
    })
}
module.exports = {
    readFiles,
    writeFiles,
    searchDate,
    mkDir
}
